package com.godyao.mall.goods.controller.front;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.godyao.mall.core.model.EsSearchParam;
import com.godyao.mall.core.model.ResultMsg;
import com.godyao.mall.core.model.goods.Goods;
import com.godyao.mall.core.model.goods.req.GoodsReq;
import com.godyao.mall.goods.service.IGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author godyao
 * @date 2022/3/31
 */
@Api(value = "商品相关接口-前台")
@RequestMapping(value = "/front")
@RestController
@RequiredArgsConstructor
public class GoodsFrontController {
    private final IGoodsService goodsService;

    @ApiOperation(value = "获取商品明细")
    @GetMapping("/goods/{goodsId}")
    public ResultMsg<Goods> findGoodsByGoodsId(@PathVariable(value = "goodsId") Long goodsId) {
        return ResultMsg.resultSuccess(goodsService.findGoodsByGoodsId(goodsId));
    }

    @ApiOperation("获取所有商品信息")
    @GetMapping("/goods")
    public ResultMsg<Page<Goods>> findPagedGoods(GoodsReq goodsReq) {
        final Specification<Object> specification = (root, query, criteriaBuilder) -> {
            final List<Predicate> predicates = new ArrayList<>();
            if (ObjectUtil.isNotNull(goodsReq) && StrUtil.isNotBlank(goodsReq.getGoodsName())) {
                final Predicate likeGoodsName = criteriaBuilder.like(root.get("goodsName").as(String.class), "%" + goodsReq.getGoodsName() + "%");
                predicates.add(likeGoodsName);
            }
            return criteriaBuilder.and(ArrayUtil.toArray(predicates, Predicate.class));
        };

        return ResultMsg.resultSuccess(goodsService.findPagedGoods(specification, PageRequest.of(goodsReq.getPageNumber()-1, goodsReq.getPageSize())));
    }

    @ApiOperation("检索商品信息")
    @GetMapping("/goods/search")
    public ResultMsg findPagedGoods(EsSearchParam param) {
        return ResultMsg.resultSuccess(goodsService.search(param));
    }

}
